/*
 * @LastEditTime: 2023-04-15 18:44:02
 */

import jwt from "jsonwebtoken";
import crypto from "crypto";
import { Context } from "koa";
const secret = "secret";
const expireIn = 10;

const algorithm = "aes-256-ctr";
const secretKey = "vOVH6sdmpNWjRRIqCc7rdxs01lwHzfr3";
const iv = crypto.randomBytes(16);

/**
 * 创建token
 * @param ctx 上下文对象
 * @param info  需要参与token的对象
 * @returns 返回一个token
 */
export const createToken = (ctx: Context, info: { username: string }) => {
  const token = jwt.sign({ ...info } || { name: "joe" }, secret);
  ctx.set("Authorization", `Bearer ${token}`);
  ctx.cookies.set("token", token, {
    maxAge: 10,
  });
  return token;
};

export const verify = (ctx: Context, decodedToken: any, token: string) => {
  let ret = true;

  try {
    decodedToken = jwt.verify(token, secret);
    ret = false;
    return ret;
  } catch (error) {
    console.error.name;
  }

  return ret;
};

/**
 * 加密
 * @param text 需要被加密的文本
 * @returns 返回密文
 */
export const encrypt = (text: any) => {
  const cipher = crypto.createCipheriv(algorithm, secretKey, iv);

  const encrypted = Buffer.concat([cipher.update(text), cipher.final()]);

  return {
    iv: iv.toString("hex"),
    content: encrypted.toString("hex"),
  };
};

/**
 * 解密
 * @param hash 哈希
 * @returns 返回解密对象
 */

export const decrypt = (hash: { iv: string; content: string }) => {
  const decipher = crypto.createDecipheriv(
    algorithm,
    secretKey,
    Buffer.from(hash.iv, "hex")
  );

  const decrpyted = Buffer.concat([
    decipher.update(Buffer.from(hash.content, "hex")),
    decipher.final(),
  ]);

  return decrpyted.toString();
};
